import {
  Dimensions,
  FlatList,
  Image,
  ImageSourcePropType,
  RefreshControl,
  ScrollView,
  StyleSheet,
  View,
} from "react-native";

import React, { Key, useContext, useEffect, useState } from "react";

import { SafeAreaView } from "react-native-safe-area-context";
import { Https } from "../../api";
import Swiper from "react-native-swiper";
import Head from "../../components/Head";
import { getHomeConfiguration } from "../../types";
import { AVPlaybackSource, ResizeMode, Video } from "expo-av";
import ImageListAuto from "../../components/ImageListAout";
import RecommendList from "../../components/RecommendList";
import { GlobalContext } from "../../hooks/reducer";

const width = Dimensions.get("window").width;
export default function Home() {
  const RecommendListConfig = {
    sceneId: "sy101",
    returnCount: 30,
    sceneType: 1,
    sourceId: 31,
  };

  const [homeList, setHomeList] = useState<[]>();
  const [refreshing, setRefreshing] = React.useState(false);

  const changeState: any = useContext(GlobalContext);

  const onRefresh = React.useCallback(() => {
    setRefreshing(true);
    wait().then(() => setRefreshing(false));
  }, []);

  useEffect(() => {
    getHomeConfiguration();

  }, []);

  const getHomeConfiguration = async () => {
    changeState.dispatch({ type: "SetToLoad", payload: true });
    const { success, data }: getHomeConfiguration =
      await Https.getHomeConfiguration({ terrace: "H5" });
    if (success) {
      setHomeList(data as unknown as undefined);
      changeState.dispatch({ type: "SetToLoad", payload: false });
    }
  };
  //下拉刷新
  const wait = () => {
    return new Promise((resolve) => {
      getHomeConfiguration().then(resolve);
    });
  };

  return (
    <SafeAreaView style={{ backgroundColor: "#fff" }}>
      <Head />

      <ScrollView
        style={{ minHeight: 800 }}
        showsVerticalScrollIndicator={false}
        keyboardDismissMode={"on-drag"}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      >
        {homeList &&
          homeList.map(
            ({
              name,
              pageBgColor,
              value: { imgList, goodsList },
              index,
            }: any) =>
              //轮播
              (name === "carouselImg" && (
                <Swiper
                  style={styles.wrapper}
                  autoplay={true}
                  dot={<View style={styles.dot} />}
                  key={index}
                  activeDot={<View style={styles.activeDot} />}
                >
                  {imgList.map(
                    (
                      items: {
                        type: String;
                        imgListImage: [{ imgUrl: String }];
                      },
                      indexTow: Key
                    ) => (
                      <View style={styles.slide} key={indexTow}>
                        {(items.type === "image" && (
                          <Image
                            style={{ height: 500, width: "100%" }}
                            source={
                              {
                                uri: items.imgListImage[0].imgUrl,
                              } as ImageSourcePropType
                            }
                          />
                        )) ||
                          (items.type === "video" && (
                            <Video
                              source={
                                {
                                  uri: items.imgListImage[0].imgUrl,
                                } as AVPlaybackSource
                              }
                              style={{
                                width: "100%",
                                height: 500,
                              }}
                              useNativeControls={false}
                              shouldPlay={true}
                              resizeMode={ResizeMode.COVER}
                              isLooping
                            />
                          ))}
                      </View>
                    )
                  )}
                </Swiper>
              )) ||
              //图片广告
              (name === "settingImage" &&
                imgList.map(({ imgUrl }: any, indexTow: Key) => (
                  <ImageListAuto
                    width={"100%"}
                    imgUrl={imgUrl}
                    key={indexTow}
                  />
                ))) ||
              //横向文图列表
              (name === "rollhorizontally" && (
                //横向滚动列表
                <FlatList
                  style={{ backgroundColor: pageBgColor }}
                  data={goodsList}
                  keyExtractor={({ buriedPoint }) => buriedPoint}
                  renderItem={({ item: { imgUrl } }) => (
                    <View>
                      <ImageListAuto
                        style={styles.crosswiseImg}
                        imgUrl={imgUrl}
                      />
                    </View>
                  )}
                  horizontal={true}
                  showsHorizontalScrollIndicator={false}
                />
              )) ||
              //特殊轮播
              (name === "imageswitch" && (
                <Swiper
                  style={{
                    height: 700,
                    backgroundColor: pageBgColor,
                    paddingTop: 20,
                  }}
                  autoplay={true}
                  dot={<View style={styles.dot} />}
                  key={index}
                  activeDot={<View style={styles.activeDot} />}
                >
                  {imgList.map(
                    (
                      items: {
                        type: String;
                        imgUrl: String;
                      },
                      indexTow: Key
                    ) => (
                      <View key={indexTow}>
                        {items.type === "image" && (
                          <ImageListAuto width={"100%"} imgUrl={items.imgUrl} />
                        )}
                      </View>
                    )
                  )}
                </Swiper>
              ))
          )}
        <RecommendList {...RecommendListConfig} />
      </ScrollView>
    </SafeAreaView>
  );
}
const styles = StyleSheet.create({
  wrapper: {
    height: 500,
  },
  dot: {
    backgroundColor: "rgba(0,0,0,.2)",
    width: 70,
    height: 4,
    borderRadius: 4,
    marginLeft: 3,
    marginRight: 3,
    marginTop: 3,
    marginBottom: 3,
  },
  activeDot: {
    backgroundColor: "rgba(0,0,0,.5)",
    width: 70,
    height: 4,
    borderRadius: 4,
    marginLeft: 3,
    marginRight: 3,
    marginTop: 3,
    marginBottom: 3,
  },
  slide: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  crosswiseImg: {
    width: width * 0.9,
    marginLeft: 10,
    marginRight: 10,
    borderRadius: 5,
  },
});
